package com.heba.fragment.scan;

import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heba.Cfg;
import com.heba.adapter.QuickAdapter;
import com.heba.bean.feature.ItemFeatureCategoryObject;
import com.heba.bean.feature.ItemFeatureProductObject;
import com.heba.bean.product.ItemProductCompareObject;
import com.heba.config.CommonConfig;
import com.heba.fragment.LazyFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.view.RoundImageView;
import com.loopj.android.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by jason on 2020/10/03.
 */
public class FeatureProductFragment extends LazyFragment {

    private LinearLayout linearCategoryView;
    private RecyclerView recyclerView;
    private QuickAdapter recycleAdapter;

    private String featureID;
    private String categoryID;
    private TextView alertLB;

    private List<ItemFeatureCategoryObject> featureCategoryObjectList;

    private List<ItemFeatureProductObject> featureProductObjectList;

    /**
     * 实例化fragment
     * 接收参数
     *
     * @param featureID
     * @return
     */
    public static FeatureProductFragment newInstance(String featureID) {
        FeatureProductFragment fragment = new FeatureProductFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.FEATURE_ID, featureID);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        featureID = bundle.getString(CommonConfig.FEATURE_ID, "");
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_feature_recyclerview, container, false);
        parseArgument();
        initView(view);
        return view;
    }

    @Override
    protected void lazyLoad() {
        getCategoryData();
    }

    private void initView(View view) {
        linearCategoryView = view.findViewById(R.id.ll_view);
        recyclerView = view.findViewById(R.id.recyclerView);
        alertLB = view.findViewById(R.id.alertLB);
        featureProductObjectList = new ArrayList<>();

        recycleAdapter = new QuickAdapter<ItemFeatureProductObject>(featureProductObjectList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.recycle_item_feature_product;
            }

            @Override
            public void convert(VH holder, ItemFeatureProductObject data, int position) {
                TextView tvTitle = holder.getView(R.id.tv_title);
                LinearLayout linearProductView = holder.getView(R.id.ll_product_view);

                tvTitle.setText(data.getName());
                if (data.getList() != null && !data.getList().isEmpty()) {
                    updateProduct(linearProductView, data.getList());
                }
            }
        };

        /**
         * 设置layoutManager布局
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(recycleAdapter);
    }

    /**
     * 更新分类view
     */
    private void updateCategoryView() {
        linearCategoryView.removeAllViews();
        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(Objects.requireNonNull(getContext()), 48));
        params.rightMargin = DensityUtils.dip2px(getContext(), 8);
        for (int i = 0; i < featureCategoryObjectList.size(); i++) {
            View view = updateCategoryRowView(featureCategoryObjectList.get(i));
            linearCategoryView.addView(view, params);
            //默认选中第一个
            if (i == 0) {
                view.setSelected(true);
                categoryID = featureCategoryObjectList.get(i).getCategoryID();
                getProductListData();
            }
        }
    }

    /**
     * 添加分类item佈局
     */
    private View updateCategoryRowView(ItemFeatureCategoryObject object) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_tab_select_layout, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getName() + " " + object.getCount());
        view.setOnClickListener(v -> {
            for (int i = 0; i < featureCategoryObjectList.size(); i++) {
                linearCategoryView.getChildAt(i).setSelected(false);
            }
            v.setSelected(true);
            categoryID = object.getCategoryID();
            getProductListData();
        });
        return view;
    }

    private void updateProduct(LinearLayout linearLayout, List<ItemProductCompareObject> productCompareObjectList) {
        linearLayout.removeAllViews();
        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT,DensityUtils.dip2px(Objects.requireNonNull(getContext()), 140));
        for (int i = 0; i < productCompareObjectList.size(); i++) {
            View view = updateProductRowView(productCompareObjectList.get(i));
            linearLayout.addView(view, params);
        }
    }

    @SuppressLint("SetTextI18n")
    private View updateProductRowView(ItemProductCompareObject object) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.item_feature_product_row2, null);
        RoundImageView iv_product = view.findViewById(R.id.goods_img);

        TextView brandName = view.findViewById(R.id.brand_txt);
        TextView productName = view.findViewById(R.id.product_txt);
        TextView kgTxt = view.findViewById(R.id.g_txt);
        TextView moneyTxt = view.findViewById(R.id.money_txt);
        brandName.setText(object.getBrandName());
        productName.setText(object.getProductName());
        kgTxt.setText(object.getPackageSize()+object.getPackageUnit());
        if(object.getMaxPrice().equals("0.00")){
            moneyTxt.setText("$ - ");
        }else{
            if(object.getMaxPrice().equals(object.getMinPrice())){
                moneyTxt.setText("$"+object.getMinPrice());
            }else{
                moneyTxt.setText("$"+object.getMinPrice()+"- $"+object.getMaxPrice());
            }
        }

        GlideUtil.loadImageWithDefaultPlaceHolder(getContext(), object.getIcon(), iv_product);
        view.setOnClickListener(v -> {
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.PRODUCT_ID, object.getProductID());
            openActivity(ItemProductDetailActivity.class, bundle);
        });
        return view;
    }

    /**
     * 获取分类数据
     */
    private void getCategoryData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("FeatureID", featureID);
        client.get(Cfg.BaseUrl + "/Feature/GetCategoryMenu", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                featureCategoryObjectList = new Gson().fromJson(array.toString(), new TypeToken<List<ItemFeatureCategoryObject>>() {
                                }.getType());
                                alertLB.setVisibility(View.GONE);
                            }else{
                                alertLB.setVisibility(View.VISIBLE);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (null != featureCategoryObjectList && !featureCategoryObjectList.isEmpty()) {
                            updateCategoryView();
                        }

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * 根据featureID和categoryID
     * 获取二级分类和产品数据
     */
    private void getProductListData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("FeatureID", featureID);
        params.put("CategoryID", categoryID);
        client.get(Cfg.BaseUrl + "/Feature/GetFirstCategoryProducts", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        if (!featureProductObjectList.isEmpty())
                            featureProductObjectList.clear();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                List<ItemFeatureProductObject> list = new Gson().fromJson(array.toString(), new TypeToken<List<ItemFeatureProductObject>>() {
                                }.getType());
                                featureProductObjectList.addAll(list);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        //刷新页面
                        recycleAdapter.notifyDataSetChanged();

                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

}
